package club.kingyin.kyblog.core.business.service.admin;

import club.kingyin.config.v2.imp.Config;
import club.kingyin.kyblog.core.business.dao.admin.Info;
import club.kingyin.kyblog.core.business.dao.admin.Token;
import club.kingyin.kyblog.core.business.dao.admin.User;
import club.kingyin.kyblog.core.business.mapper.admin.UserMapper;
import club.kingyin.kyblog.core.business.service.DocService;
import club.kingyin.kyblog.core.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : kingyins
 * @version : 1.0
 * @program : Ky-Blog
 * @description : 在此处添加类描述
 * @create : 2021年08月19日 14:17
 **/
@Service
@Repository
public class AdminService {

    @Autowired
    private Config config;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DocService docService;

    @Autowired
    private AuthorityService authorityService;


    public Token login(User user) {
        User login = userMapper.login(user);
        if (login == null)
            return null;
        Token token = new Token();
        String s = TokenUtil.getToken(user);
        token.setToken(s);
        authorityService.publish(s);
        return token;
    }

    public Info getInfo(String token) {
        try {
            Info info = new Info();
            User user = TokenUtil.deToken(token, User.class);
            user = userMapper.selectUserInfo(user);
            info.setAvatar(user.getAvatar());
            info.setIntroduction(user.getIntroduction());
            info.setName(user.getName());
            info.setRoles(new String[]{"admin"});
            return info;
        } catch (Exception ignored) {

        }
        return null;
    }

    @Transactional
    public boolean update(String token, String name) {
        try {
            User user = TokenUtil.deToken(token, User.class);
            user.setName(name);
            config.put("author",name);
            userMapper.update(user);
            docService.updateAuthor(name);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean logout(String token) {
        return authorityService.repeal(token);
    }

}
